// CHLocationManager.m

#import "CHLocationManager.h"
#import "HomeRequest.h"

static CHLocationManager *_sharedInstance = nil;

@interface CHLocationManager ()

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation CHLocationManager

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //        [self startUpdatingLocation];
    }
    return self;
}

- (void)startUpdatingLocation {
    CLAuthorizationStatus status = [self.locationManager authorizationStatus];
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            [self.locationManager requestWhenInUseAuthorization];
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            [self.locationManager startUpdatingLocation];
            break;
        case kCLAuthorizationStatusDenied:
        case kCLAuthorizationStatusRestricted:
            
            break;
    }
}

- (void)stopUpdatingLocation {
    [self.locationManager stopUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    self.currentLocation = locations.lastObject;
    if(self.locationBlock){
        
        self.locationBlock(1,  self.currentLocation);
    }
    [self.locationManager stopUpdatingLocation];
    CLLocation *currentLocation = locations.lastObject;
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    __weak typeof(self) weakSelf = self;
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Error in reverse geocoding: %@", error.localizedDescription);
        } else {
            if (placemarks.count > 0) {
                CLPlacemark *placemark = placemarks[0];
                NSString *province = placemark.administrativeArea;
                NSString *city = placemark.locality;
                NSString *district = placemark.subLocality;
                NSString *country = placemark.country;
                NSString *countryCode = placemark.ISOcountryCode;
                NSString *street = placemark.thoroughfare;
                if (city) {
                    NSLog(@"City: %@", city);
                    
                    NSMutableDictionary *dicInfo = [NSMutableDictionary dictionary];
                    [dicInfo setValue:CHString(country) forKey:@"choke"];
                    [dicInfo setValue:CHString(countryCode) forKey:@"piece"];
                    [dicInfo setValue:CHString(CHStringIsEmpty(province)?city:province) forKey:@"hoping"];
                    [dicInfo setValue:CHString(city) forKey:@"swork"];
                    [dicInfo setValue:CHString(district) forKey:@"told"];
                    [dicInfo setValue:CHString(street) forKey:@"pretended"];
                    [dicInfo setValue:[NSString stringWithFormat:@"%.6f",currentLocation.coordinate.latitude] forKey:@"work"];
                    [dicInfo setValue:[NSString stringWithFormat:@"%.6f",currentLocation.coordinate.longitude] forKey:@"secret"];
                    [weakSelf requestUploadLocationInfo:dicInfo];
                    
                } else {
                    NSLog(@"City not found.");
                }
            }
        }
    }];
    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
    if(self.locationBlock){
        
        self.locationBlock(-1, [CLLocation new]);
    }
}

- (void)requestUploadLocationInfo:(NSDictionary *)dicLocation{
    
    [HomeRequest requestUploadLocation:dicLocation success:^(NSURLSessionDataTask *task, id response) {
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}
- (void)checkLocationPermission {
    
    CLAuthorizationStatus status = [self.locationManager authorizationStatus];
    if(status == kCLAuthorizationStatusDenied ||
       status == kCLAuthorizationStatusRestricted){
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSMutableDictionary *dicAuth = [NSMutableDictionary dictionaryWithDictionary:[defaults dictionaryForKey:@"LocationAlertAuth"]];

        if(dicAuth.count > 0&&[CHString(dicAuth[@"show"]) isEqualToString:@"1"]){
            
            NSDate *currentDate = [NSDate date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            NSString *formattedDate = [dateFormatter stringFromDate:currentDate];
          
            [dicAuth setObject:@"2" forKey:@"show"];
            [dicAuth setObject:formattedDate forKey:@"date"];
            [defaults setObject:dicAuth forKey:@"LocationAlertAuth"];
            [defaults synchronize];
            
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"The location permission is not enabled" message:@"To better use the functions of the application, enable the location permission." preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"Go to Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
          
                NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
                    [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
                }
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:settingsAction];
            [alert addAction:cancelAction];
            [[UIView xhl_getTopViewController] presentViewController:alert animated:YES completion:nil];
            
        }
        
    }
}

@end
